package com.yfree.utils;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.webkit.JavascriptInterface;

import com.google.gson.Gson;
import com.yfree.YConfig;
import com.yfree.activities.YActivity;
import com.yfree.activities.YWebActivity;
import com.yfree.activities.YWebActivity2;
import com.yfree.application.YApplication;
import com.yfree.libs.dsbridge.CompletionHandler;
import com.yfree.views.YProgressDialog;
import com.yfree.views.YWebView;

import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class YJSDelegate {
    public static final String instance = "yPhone";
    public YActivity yActivity;
    public YWebView webView;

    public YJSDelegate(YActivity yActivity, YWebView webView) {
        this.yActivity = yActivity;
        this.webView = webView;
    }

    @JavascriptInterface
    public String getDevice(Object param) {
        return YConfig.device;
    }

    @JavascriptInterface
    public String getAppName(Object param) {
        return YAppUtils.getAppName(yActivity);
    }

    @JavascriptInterface
    public String getVersion(Object param) {
        return String.valueOf(YVersionUtils.getVersionCode(yActivity));
    }

    @JavascriptInterface
    public String getIP(Object param) {
        return YConfig.IP;
    }

    @JavascriptInterface
    public String getDebug(Object param) {
        return YConfig.DEBUG ? "1" : "0";
    }

    @JavascriptInterface
    public String getHttpHeader(Object param) {
        return "{}";
    }

    @JavascriptInterface
    public String getUserEntity(Object param) {
        return "";
    }

    @JavascriptInterface
    public void closeKeyBoard(Object param) {
        yActivity.yCloseInputMethod();
    }

    @JavascriptInterface
    public void openQQ(Object param) {
        YQQUtils.openQQ(yActivity, param.toString());
    }

    @JavascriptInterface
    public void goBack(Object param) {
        webView.goBack();
    }

    @JavascriptInterface
    public void close(Object param) {
        yActivity.finish();
    }

    @JavascriptInterface
    public void close2(Object param) {
        yActivity.finish();
    }

    @JavascriptInterface
    public void openBrowser(Object param) {
        yActivity.startActivity(new Intent().setAction(Intent.ACTION_VIEW).setData(Uri.parse(param.toString())));
    }

    @JavascriptInterface
    public void log(Object param) {
        yActivity.yLog(param.toString());
    }

    @JavascriptInterface
    public void toast(Object param) {
        yActivity.yToast(param.toString().replace("<br/>", "\n"));
    }

    @JavascriptInterface
    public void showProgress(Object param) {
        YProgressDialog.showProgress(yActivity);
    }

    @JavascriptInterface
    public void dismissProgress(Object param) {
        YProgressDialog.dismissProgress(yActivity);
    }

    @JavascriptInterface
    public void copy(Object param) {
        ((ClipboardManager) yActivity.context.getSystemService(Context.CLIPBOARD_SERVICE)).setPrimaryClip(ClipData.newPlainText("text", param.toString()));
    }

    @JavascriptInterface
    public void post(Object param, CompletionHandler<String> handler) {
        try {
            JSONObject jsonObj = ((JSONObject) param);
            String ip = jsonObj.getString("IP");
            String jkid = jsonObj.getString("jkid");
            JSONObject params = jsonObj.getJSONObject("params");
            AjaxParams kv = new AjaxParams();
            kv.put("jkid", jkid);
            kv.put("jkparam", params.toString());
            YApplication.getFinalHttp().post(ip, kv, new AjaxCallBack<String>() {
                @Override
                public void onSuccess(String t) {
                    Map<String, Object> map = new HashMap<>();
                    if (t != null) {
                        map.put("code", 1);
                        map.put("result", t);
                    } else {
                        map.put("code", 0);
                        map.put("message", YConfig.DEBUG ? "网络请求响应为空" : "网络请求错误，请重试");
                    }
                    handler.complete(new Gson().toJson(map));
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("code", 0);
                    map.put("message", YConfig.DEBUG ? "网络请求异常！！！" + strMsg : "网络请求错误，请重试");
                    handler.complete(new Gson().toJson(map));
                }
            });
        } catch (Exception e) {
            Map<String, Object> map = new HashMap<>();
            map.put("code", 0);
            map.put("message", YConfig.DEBUG ? "网络请求异常！！！" + e.getLocalizedMessage() : "网络请求错误，请重试");
            handler.complete(new Gson().toJson(map));
        }
    }

    // self
    public void yEvaluateScript(String script) {
        if (yActivity instanceof YWebActivity) ((YWebActivity) yActivity).yEvaluateScript(script);
        else if (yActivity instanceof YWebActivity2) ((YWebActivity2) yActivity).yEvaluateScript(script);
    }
}
